package com.eqdd.yiqidian.ui.gongneng.renshi.finance

import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView

import com.eqdd.yiqidian.R
import com.eqdd.yiqidian.base.Config
import com.eqdd.yiqidian.bean.CheckerBean
import com.eqdd.yiqidian.bean.ExpenseSettingBean
import com.eqdd.yiqidian.http.*
import com.eqdd.yiqidian.kotlin.KotlinBaseActivity
import com.eqdd.yiqidian.utils.ToastUtil
import com.google.gson.Gson
import com.lzy.okgo.OkGo
import com.lzy.okgo.model.Response
import kotlinx.android.synthetic.main.activity_expense_setting.*
import kotlinx.android.synthetic.main.list_item_121.view.*
import org.jetbrains.anko.forEachChild
import org.jetbrains.anko.sdk25.coroutines.onClick
import org.jetbrains.anko.sdk25.coroutines.onFocusChange
import org.jetbrains.anko.startActivityForResult
import org.jetbrains.anko.toast


/**
 * @author吕志豪 .
 * @date 18-3-20  上午10:57.
 * Github :https://github.com/lvzhihao100
 * E-Mail：1030753080@qq.com
 * 简书 :http://www.jianshu.com/u/6e525b929aac
 */

class ExpenseSettingActivity : KotlinBaseActivity() {
    private var isReSetting: Boolean = false
    val setData: HashSet<CheckerBean> = hashSetOf()

    override fun onCreate(savedInstanceState: Bundle?) {
        setContentView(R.layout.activity_expense_setting)
        super.onCreate(savedInstanceState)

    }

    private fun initTopBar() {
        val inflater = LayoutInflater.from(this)
        if (isReSetting) {
            initTopBar("报销设置", "重新设置", View.OnClickListener {
                recyclerView.removeAllViews()
                reSetting()
            })
        } else {
            tv_add.visibility = View.VISIBLE
            addView(inflater)
            initTopBar("报销人和金额设置", "完成", View.OnClickListener { upLoad() })
        }
    }

    private fun upLoad() {

        val list: ArrayList<Params> = arrayListOf()
        recyclerView.forEachChild { view ->
            val bean = Params()
            bean.minMoney = view.tv_start_money.text.toString().toInt()
            bean.maxMoney = view.tv_end_money.text.toString().toInt()
            val postList = setData.filter { it.name == view.tv_checker.text }
            if (bean.minMoney > bean.maxMoney) {
                toast("金额设置中有最小金额大于最大金额")
                return
            }
            if (postList.isNotEmpty()) {
                if (postList.map { it.id }.isNotEmpty()) {
                    bean.postId = postList.map { it.id }[0]
                } else {
                    toast("请设置最终报销审核人")
                    return
                }
            } else {
                toast("请设置最终报销审核人")
                return
            }
            list.add(bean)
        }
        val params = Gson().toJson(list)
        OkGo.post<HttpResult<*>>(HttpConfig.BASE_URL + HttpConfig.EXPENSE_CHECKER)
                .params("userGuid", user?.guid.orEmpty())
                .params("companyId", user?.companyId?.toString())
                .params("parameter", params)
                .execute(object : HttpCallBack<HttpResult<*>>(this@ExpenseSettingActivity) {

                    override fun onSuccess(response: Response<HttpResult<*>>) {
                        val httpResult = response.body()
                        ToastUtil.showShort(httpResult.msg)
                        if (httpResult.status == 200) {
                            setResult(Config.SUCCESS)
                            finish()
                        }
                    }

                    override fun onError(response: Response<HttpResult<*>>?) {
                        super.onError(response)
                    }
                })
    }

    private fun reSetting() {
        isReSetting = false
        initTopBar()
        val inflater = LayoutInflater.from(this)
        tv_add.onClick {
            addView(inflater)
        }


    }

    private var tvChecker: TextView? = null

    fun addView(inflater: LayoutInflater) {

        val view = inflater.inflate(R.layout.list_item_119, null)
        val child = recyclerView.childCount + 1
        view.tag = child
        val tag = view.tag as Int

        if (recyclerView.childCount == 0) {
            view.tv_start_money.text = 0.toString()
            view.tv_end_money.text = 999.toString()
        } else {
            recyclerView.forEachChild {
                if (tag == recyclerView.childCount + 1) {
                    val min = it.tv_end_money.text.toString().toInt() + 1
                    val max = min + 999
                    view.tv_start_money.text = min.toString()
                    view.tv_end_money.text = max.toString()
                }
            }
        }



        view.tv_end_money.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {
                if (tag != recyclerView.childCount) {
                    recyclerView.forEachChild {
                        if (it.tag as Int == tag + 1) {
                            val min = view.tv_end_money.text.toString().toInt() + 1
                            it.tv_start_money.text = min.toString()
                        }
                    }
                }
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
        })

        view.tv_end_money.onFocusChange { v, hasFocus ->
            if (!hasFocus) {
                if (view.tv_end_money.text.toString().toInt() < view.tv_start_money.text.toString().toInt()) {
                    toast("最大金额小于最小金额,请修改金额")
                }
            }
        }


        view.tv_checker.onClick {
            tvChecker = view.tv_checker
            startActivityForResult<CheckerListActivity>(100)
        }


        view.setOnLongClickListener { v ->
            if (!isReSetting && tag == recyclerView.childCount) {
                recyclerView.removeView(v)
            }
            true

        }
        recyclerView.addView(view)
    }


    override fun initData() {
        OkGo.post<HttpResult<List<ExpenseSettingBean>>>(HttpConfig.BASE_URL + HttpConfig.EXPENSE_LIST)
                .params("userGuid", user?.guid.orEmpty())
                .params("companyId", user?.companyId?.toString())
                .execute(object : HttpCallBack<HttpResult<List<ExpenseSettingBean>>>(this@ExpenseSettingActivity) {

                    override fun onSuccess(response: Response<HttpResult<List<ExpenseSettingBean>>>) {

                        val httpResult = response.body()
                        ToastUtil.showShort(httpResult.msg)
                        if (httpResult.status == 200 && httpResult.items.orEmpty().isNotEmpty()) {
                            setResult(Config.SUCCESS)
                            isReSetting = true
                            setView(httpResult.items)
                        } else {
                            isReSetting = false
                        }
                        initTopBar()
                    }
                })

    }

    private fun setView(items: List<ExpenseSettingBean>?) {
        tv_add.visibility = View.GONE
        val inflater = LayoutInflater.from(this)
        if (items.orEmpty().isNotEmpty()) {
            items?.forEach {
                val view = inflater.inflate(R.layout.list_item_121, null)
                view.tv_start_money.text = it.minMoney.toString()
                view.tv_end_money.text = it.maxMoney.toString()
                view.tv_checker.text = it.postName + "-" + it.checkName
                recyclerView.addView(view)
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 100 && resultCode == RESULT_OK) {
            val bean = data?.getSerializableExtra("data") as CheckerBean
            tvChecker?.text = bean.name
            setData.add(bean)
        }


    }

    class Params {
        var minMoney = 0
        var maxMoney = 0
        var postId = 0
    }

}
